<template>
	<form class="form-box" @change="formChange()">
  	<div class="create-publishing common-content-style">
	  	<div>
	  		<span><span @click="backFillData(fullText,'-1')" class="cursor" :class="clickIndex==0?'bolder':''" style="color: #333">全文</span></span>
	  		<span v-for="(item,index) in allArticle" ><span class="unscramble cursor" @click="backFillData(item,index)" :class="clickIndex==index+1?'bolder':''" >解读{{index+1}}</span><b @click="deleteUunscramble(item.id,index)" v-if="currentType!='lookOver'">x</b></span>
	  		<span class="Public-btn btn" @click="addUnscramble()" v-if="currentType!='lookOver'">添加解读</span>
	  	</div>
	  	<p>
				<span><span>*</span>标题</span>
				<span style="width: 1020px;" :title="article.articleTitle">
					<input class="input" v-model="article.articleTitle" name="articleTitle"  style="width: 828px;" required/>
				</span>
	  	</p>
			<p>
				<span><span>*</span>文件时间</span>
				<input  id="applyDate" class="input" name="articleFileDate" required  autocomplete="off"/>
				<span><span>*</span>文件号</span>
				<span style="width: 750px;" :title="article.articleFileNumber">
					<input type="text" class="input" name="articleFileNumber"   style="width: 514px;" v-model="article.articleFileNumber"  required/>
				</span>
			</p>
			<div :class="!clickIndex?'':'hide-input'">
				<span><span>*</span>政策类型</span>
				<multi :optionsdata="selectPublish" :selecteddata="selectedPublish" @item="obtainContent" :dataindex="2" :displayname="'value'" :initialization="'请选择政策类型'"></multi>
				<span :class="content?'hide-input':'error'">请选择内容</span>
				<span><span>*</span>性质分类</span>
				<multi :optionsdata="selectNature" :selecteddata="selectedNature" @item="obtainNature" :dataindex="5" :displayname="'value'" :initialization="'请选择性质分类'"></multi>
				<span :class="nature?'hide-input':'error'">请选择性质</span>
				<span><span>*</span>地区</span>
				<select class="select" v-model="article.area" name="area" required>
					<option v-for="item in regionList" :value="item.id">{{item.value}}</option>
				</select>
			</div>
			<div v-if="!clickIndex">
				<span style="width: 76px;margin-left: 10px;">头图上传</span>
				<span class="Public-btn btn" @click="uploadImg()">上传</span>
				<img :src="article.articleCoverUrl" v-if="article.articleCoverUrl">
				<span class="Public-btn btn" @click="deleteImg()" v-if="article.articleCoverUrl">删除头图</span>
				<span class="suggest"><span>建议上传尺寸150px*100px</span></span>
				<input accept="image/*"  class="transfer-img" id="xdaTanFileImg" @change="ObtainImg()">
				<!-- type="file"  -->
			</div>
			<div v-if="clickIndex">
				<span><span>*</span>类型</span>
				<select class="select" name="type" v-model="article.status" required>
					<option value="3">转载</option>
					<option value="4">原创</option>
				</select>
			</div>
			<p>
				<span><span>*</span>正文</span>
				<span :class="articleContent?'hide-input':'error'">请输入正文</span>
			</p>
	    <div class="editor-container">
	      <UE :defaultMsg=defaultMsg :config=config ref="ue"></UE>
	    </div>
	    <p class="btn">
	    	<input type="submit"  class="Public-btn" value="保存" @click="type('1')" v-if="currentType!='lookOver'">
	    	<input type="submit"  class="Public-btn" value="发布" @click="type('2')" v-if="currentType!='lookOver'&&!clickIndex">
	    	<input class="Public-btn" value="返回" @click="type('3')" v-if="currentType=='lookOver'">
	    </p> 
  	</div>
  </form>  
</template>

<script>
	import UE from "../shareComponent/UE";
	import multi from "../shareComponent/multiSelect";
	import "../../static/js/jquery.datetimepicker.full.js";
	import "../../static/js/jquery-validation.js";
	import "../../static/js/validation-message.js";
	export default {
    name:'create-publishing',
    data: function(){
      return{
      	/*添加解读数量*/
      	addList:[],
      	/*富文本回填数据*/
        defaultMsg: "",
        config: {
          initialFrameWidth: null,
          initialFrameHeight: 350
        },
        /*下拉内容多选数据*/
       	selectPublish:[],
        selectedPublish:[],
        /*下拉性质多选数据*/
       	selectNature:[],
        selectedNature:[],
        /*地区*/
        regionList:[],
        /*上传图片src*/
        imgSrc:"",
        /*全部数据*/
       	allArticle:[],
       	/*全文数据*/
       	fullText:{},
        /*显示数据*/
        article:{
        	type:"11",
        	/*标题*/
        	articleTitle:"",
        	/*文件时间*/
        	articleFileDate:"",
        	/*文件号*/
        	articleFileNumber:"",
        	/*二级属性(政策内容/性质)*/
        	parentCategory:"2,3",
        	/*底层属性(个税等)*/
        	childCategory:"",
        	/*地区*/
        	area:"",
        	/*头图*/
        	articleCoverUrl:"",
        	/*内容*/
        	contentChildCategory:[],
        	/*性质*/
        	natureChildCategory:[],
        	/*正文*/
        	articleContent:"",
        	/*类型*/
        	status:"3"
        },
        /*当前点击是发布还是保持*/
        status:"",
        /*性质提示语显示与否*/
        nature:"1",
        /*内容提示语显示与否*/
        content:"1",
        /*正文提示语显示与否*/
        articleContent:"true",
        /*页面是否进行了改变*/
        articleChange:false,
        /*当前页面是新增，修改，查看页面*/
      	currentType:"",
      	/*切换tab下标*/
      	clickIndex:0,
      	/*回填数据条数*/
      	articleLength:0,
      	/*当前页面下标值*/
      	currentIndex:-2,
      	/*当前页面是否为新增解读*/
      	isAdd:-2,
      	/*新增解读*/
      	addMsg:false,
      	/*全文id*/
      	id:"",
      	/*第一次保存全文/修改/查看*/
      	oneTime:false,
      }
    },
    components:{UE,multi},
    mounted:function() {
    	$(".show-select-name").css({"width":"200px","height":"36px","border": "1px solid #ccc","cursor":"pointer"});
    	$(".all-option").css("width","200px");
      $('#applyDate').datetimepicker({format:"Y-m-d H:i:s",step:1,maxDate:new Date()});
      $.datetimepicker.setLocale('ch');
    	$("#xdaTanFileImg").attr("type","file");
	  	var  _this= this;
      $.validator.setDefaults({
        submitHandler: function() {
        	/**校验成功后通常调接口**/
        	_this.submitBtn();
        }
      });
			/**校验规则**/
      this.validator = $(".form-box").validate({
        rules:{
          articleTitle:{
            required:true,
            maxlength: 100
          },
          articleFileDate:{
            required:true,
          },
          articleFileNumber:{
            required:true,
            maxlength: 100
          },
          area:{
            required:true,
          },
          type:{
            required:true,
          },
        },
        messages:{
          articleTitle:{
            required:"请输入标题"
          },
          articleFileDate:{
            required:'请选择时间'
          },
          articleFileNumber:{
            required:'请输入文件号'
          },
          area:{
            required:'请选择地区'
          },
          subSystermAddr:{
            required:'请输入子系统地址'
          },
         	type:{
         		required:'请选择类型'
         	}
        }
      });
      /*当前页面是新增，修改，查看页面*/
      this.currentType=this.$route.query.currentType;
      /*获取内容下拉框值*/
    	/*获取性质下拉框值*/
      this.queryContent();
      /*获取回显数据*/
      if(this.$route.query.currentType=="modify"||this.$route.query.currentType=="lookOver"){
      	this.id=this.$route.query.id;
      	this.oneTime=true;
     		this.queryAllData();
      }
    },
   
    methods:{
    	type:function(type){
    		if(type==3) {
          this.$router.push({path: '/main/policyRelease'});
        }
    		this.status=type;
    	},
    	/*表单是否被改变*/
    	formChange:function(){
    		this.articleChange=true;
    	},
    	/*获取内容下拉框值*/
    	/*获取性质下拉框值*/
    	queryContent:function(){
    		this.$get('/system/queryDataByParentId/1')
    		.then(response => {
    			/*未登录重定向*/
          if(response==444){
          	this.$router.push({path: '/login'});
          }else{
          	if (response.resultCode ==0) {
	            this.regionList=response.resultData;
	            this.article.area=this.regionList[0].id;
	          }else{
	          	layer.alert(response.resultMsg);
	          }
          }
         
        }).catch(err => {
          console.log(err);
        });
    		this.$get('/system/queryDataByParentId/2')
    		.then(response => {
    			/*未登录重定向*/
          if(response==444){
          	this.$router.push({path: '/login'});
          }else{
          	if (response.resultCode ==0) {
	            this.selectPublish=response.resultData;
	          }else{
	          	layer.alert(response.resultMsg);
	          }
          }
         
        }).catch(err => {
          console.log(err);
        });
        this.$get('/system/queryDataByParentId/3')
    		.then(response => {
    			/*未登录重定向*/
          if(response==444){
          	this.$router.push({path: '/login'});
          }else{
          	if (response.resultCode ==0) {
	            this.selectNature=response.resultData;
	          }else{
	          	layer.alert(response.resultMsg);
	          }
          }
         
        }).catch(err => {
          console.log(err);
        });
    	},
    	/*获取回显数据*/
    	queryAllData:function(){
    		this.$post(
          '/article/queryArticle',
          {
	          id:this.id,
	          bringChild:"child"
          }
        )
    		.then(response => {
    			/*未登录重定向*/
          if(response==444){
          	this.$router.push({path: '/login'});
          }else{
          	if (response.resultCode ==0) {
          		var allArticle=[];
          		this.allArticle=[];
	            allArticle = response.resultData.articleVoList;
	            this.articleLength= response.resultData.articleVoList.length;
	            for(var i=1;i<allArticle.length;i++){
	            	allArticle[i].publishAt=this.formatTime(allArticle[i].publishAt);
	            	allArticle[i].fileDate=this.formatTime(allArticle[i].fileDate);
	            	this.allArticle.push(allArticle[i]);
	            }
	            allArticle[0].publishAt=this.formatTime(allArticle[0].publishAt);
            	allArticle[0].fileDate=this.formatTime(allArticle[0].fileDate);
	            this.fullText=allArticle[0];
	            if(this.oneTime){
	            	this.backFillData(allArticle[0],'-1',"frist");
	            }
	           
	          }else{
	          	layer.alert(response.resultMsg);
	          }
          }
         
        }).catch(err => {
          console.log(err);
        })
    	},
    	commonFillData:function(singleData,index){
    		this.clickIndex=parseInt(index)+1;
    		this.article={
	      	/*标题*/
	      	articleTitle:singleData.title,
	      	/*文件时间*/
	      	articleFileDate:singleData.fileDate,
	      	/*文件号*/
	      	articleFileNumber:singleData.fileNumber,
	      	/*地区*/
	      	area:singleData.area,
	      	/*头图*/
	      	articleCoverUrl:singleData.coverUrl,
	      	/*正文*/
	      	articleContent:singleData.content,
	      	/*内容*/
	      	contentChildCategory:singleData.contentList,
	      	/*性质*/
	      	natureChildCategory:singleData.typeList,
	      	type:singleData.type,
	      	status:singleData.status
	      }
    		/*id*/
    		if(this.allArticle.length!=this.articleLength){
        	this.article.id=singleData.id?singleData.id:"";
        }
    		
    		this.selectedPublish=singleData.contentList;
    		this.selectedNature=singleData.typeList;
	      $("#applyDate").val(this.article.articleFileDate);
	      this.defaultMsg=singleData.content;
    	},
    	/*数据回填页面显示数据*/
    	backFillData:function(singleData,index,unscramble){
    		var _this=this;
    		if(this.currentIndex==index){
    			return;
    		}
    		if(unscramble!='frist'){
    			let content = this.$refs.ue.getUEContent();
	       	if(this.defaultMsg!=content){
	       		this.formChange();
	       	}
    		}
  		  if(this.articleChange&&unscramble!="unscramble"&&this.currentType!="lookOver"){
					var indexs=layer.confirm('当前内容已被修改，离开将不会保存，确定要离开吗？', {
						title:"保存提示",
						btnAlign:"c",
					  btn: ['确定','取消'] //按钮
					}, function(){
						layer.close(indexs);
						if(_this.isAdd==_this.allArticle.length){
  		  			_this.allArticle.splice(_this.allArticle.length-1,1);
  		  		}
	      		_this.commonFillData(singleData,index);
	      		_this.currentIndex=index;
	      		_this.articleChange=false;
	      		_this.addMsg=false;
	      	})
				}else{
					this.commonFillData(singleData,index);
					this.currentIndex=index;
				}
    		
    	},
    	/*添加解读*/
      addUnscramble:function(){
      	var _this=this;
      	if(this.$route.query.currentType=="add"&&!this.id){
				  layer.open({
				  	title: '添加解读提示',
					  content: '请先保存全文后，再进行添加'
					}); 
      	}else{
      		var article={
	        	/*标题*/
	        	title:this.fullText.title,
	        	/*文件时间*/
	        	fileDate:this.fullText.fileDate,
	        	/*文件号*/
	        	fileNumber:this.fullText.fileNumber,
	        	/*正文*/
	        	content:"",
	        	contentList:[],
	        	typeList:[],
	        	type:"13",
	        	status:"3"
	        };
	        let content = this.$refs.ue.getUEContent();
	       	if(this.defaultMsg!=content){
	       		this.formChange();
	       	}
	       	if(this.articleChange&&!this.allArticle.length){
	       		layer.open({
					  	title: '保存提示',
						  content: '请保存全文'
						}); 
						return;
	       	}
	        if(this.articleChange){
	        	layer.open({
					  	title: '保存提示',
						  content: '内容已被修改，请先保存'
						}); 
						return;
						/*layer.confirm('当前内容已被修改，离开将不会保存，确定要离开吗？', {
							title:"保存提示",
							btnAlign:"c",
						  btn: ['确定','取消'] //按钮
						}, function(){
		      		_this.allArticle.push(article);
		      		_this.backFillData(article,_this.allArticle.length-1,'unscramble');
		      	})*/
					}else{
						this.allArticle.push(article);
						this.isAdd=this.allArticle.length;
		      	this.backFillData(article,this.allArticle.length-1,'unscramble');
					}
					this.articleChange=true;
      	}
      },
      /*代码触发图片上传事件*/
      uploadImg:function(){
      	$("#xdaTanFileImg").attr("type","file");
      	$(".transfer-img").click();
      },
      /*获取图片*/
      ObtainImg:function(){
     		var picFile = document.getElementById("xdaTanFileImg");
     		var formdata1=new FormData();// 创建form对象
				formdata1.append('file',picFile.files[0]);
				let config = {
				  headers:{'Content-Type':'multipart/form-data'}
				}; 
      	this.$post('/system/uploadFile',formdata1,config)
    		.then(response => {
    			/*未登录重定向*/
          if(response==444){
          	this.$router.push({path: '/login'});
          }else{
          	if (response.resultCode ==0) {
	          this.article.articleCoverUrl=this.prefixUrl+response.resultData;
	          $("#xdaTanFileImg").attr("type","text");
	          }else{
	          	layer.alert(response.resultMsg);
	          }
          }
         
        }).catch(err => {
          console.log(err);
        })
      	
      },
      /*保存或者发布文件*/
      submitBtn:function(){
      	var date=$("#applyDate").val();
      	this.content=this.article.contentChildCategory.length;
      	this.nature=this.article.natureChildCategory.length;
      	let content = this.$refs.ue.getUEContent();
        this.article.articleContent=content;
        this.articleContent=content;
      	
      	if(!this.clickIndex){
      		if(!this.content||!this.nature||!this.articleContent){
	      		return;
	      	}
      		this.article.childCategory="";
	      	for(var i=0;i<this.content;i++){
	      		this.article.childCategory+=this.article.contentChildCategory[i].id+",";
	      	}
	      	for(var i=0;i<this.nature;i++){
	      		this.article.childCategory+=this.article.natureChildCategory[i].id+",";
	      	}
	      	this.article.childCategory=this.article.childCategory.substring(0,this.article.childCategory.length-1);
					
					this.article.status=this.status;
      	}else{
      		if(!this.articleContent){
	      		return;
	      	}
      		this.article.parentId=this.fullText.id
      	}
      	this.article.articleFileDate=date.substring(0,4)+date.substring(5,7)+date.substring(8,10)+date.substring(11,13)+date.substring(14,16)+date.substring(17,19);
       /* delete this.article.contentChildCategory;
        delete this.article.natureChildCategory;*/
        if(this.allArticle.length==this.articleLength||this.addMsg){
        	this.addArticle();
        }else{
        	this.updateArticle();
        }
      	
      },
      addArticle:function(){
      	var _this=this;
      	this.$post('/article/addArticle',this.article)
    		.then(response => {
    			/*未登录重定向*/
          if(response==444){
          	this.$router.push({path: '/login'});
          }else{
          	if (response.resultCode ==0) {
          		this.addMsg=false;
          		this.article.id=response.resultData;
          		if(this.status==2){
          			this.$router.push({path: '/main/policyRelease'});
          		}else{
          			if(JSON.stringify(this.fullText) == "{}"){
          				this.id=response.resultData;
          				this.oneTime=true;
          			}else{
          				this.oneTime=false;
          			}
          			this.queryAllData();
          			_this.articleChange=false;
          			_this.defaultMsg=_this.article.articleContent;
          			layer.alert("保存成功");
          		}
	          }else{
	          	layer.alert(response.resultMsg);
	          }
          }
         
        }).catch(err => {
          console.log(err);
        })
      },
      updateArticle:function(){
      	var _this=this;
      	this.$post('/article/updateArticle',this.article)
    		.then(response => {
    			/*未登录重定向*/
          if(response==444){
          	this.$router.push({path: '/login'});
          }else{
          	if (response.resultCode ==0) {
          		if(this.status==2){
          			this.$router.push({path: '/main/policyRelease'});
          		}else{
          			this.oneTime=false;
          			this.queryAllData();
          			_this.articleChange=false;
          			_this.defaultMsg=_this.article.articleContent;
          			layer.alert("保存成功");
          		}
	          }else{
	          	layer.alert(response.resultMsg);
	          }
          }
         
        }).catch(err => {
          console.log(err);
        })
      },
      /*删除解读*/
			deleteUunscramble:function(id,index){
				var _this=this;
				let content = this.$refs.ue.getUEContent();
       	if(this.defaultMsg!=content){
       		this.formChange();
       	}
       /*	if(this.articleChange){
        	layer.open({
				  	title: '保存提示',
					  content: '内容已被修改，请先保存'
					}); 
					return;
				}*/
				layer.confirm('您确定要删除这条解读吗？', {
					title:"删除",
					btnAlign:"c",
				  btn: ['确定','取消'] //按钮
				}, function(){
					if(_this.isAdd==_this.allArticle.length||_this.addMsg){
						_this.allArticle.splice(index,1);
						_this.addMsg=false;
	          layer.alert("删除成功");
					}else{
						_this.$get('/article/delArticle/'+id)
		    		.then(response => {
		    			/*未登录重定向*/
		          if(response==444){
		          	_this.$router.push({path: '/login'});
		          }else{
		          	if (response.resultCode ==0) {
		          		_this.allArticle.splice(index,1);
		          		layer.alert("删除成功");
		          	}
		          }
		        })
					}
					_this.articleChange=false;
	        _this.backFillData(_this.fullText,'-1',"frist");
	        
	    	})
			},
      /*获取内容*/
      obtainContent:function(data){
      	this.article.contentChildCategory=data;
      	this.formChange();
      },
       /*获取性质*/
      obtainNature:function(data){
      	this.article.natureChildCategory=data;
      	this.formChange();
      },
      /*删除头图*/
      deleteImg:function(){
      	this.article.articleCoverUrl="";
      	this.formChange();
      },
    }
	}
	
</script>
<style lang="less" scoped>
	.create-publishing{
		>div:first-child{
			padding-bottom: 10px;
			border-bottom: 1px solid #ccc;
			margin-bottom: 20px;
			>span{
				text-align: center;
				>span.unscramble{
				  margin-left: 10px;
					width:50px ;
					color: #333;
					
				}
				>.bolder{
					font-weight: bold;
				}
				>b{
					margin-left: 4px;
					padding: 4px;
					cursor: pointer;
				}
				>b:hover{
					color: #11d7f4;
				}
			}
			
			>button{
				margin-left: 10px;
			}
		}
		>p,div{
			> img{
				width: 150px;
				height: 100px;
			}
			>span{
				width: 86px;
			}
			>span.btn{
				line-height: 36px;
				text-align: center;
			}
			.input,.select{
				width: 200px;
				margin-right: 20px;
			}
		}
		>p.btn{
			>input{
				width: 70px;
				text-align: center;
			}
		}
		div.multi{
			width: 200px;
			display: inline-block;
	    top: 14px;
	    margin-right: 20px;
		}
		
	}
</style>
